package ay.shadow.core.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.SignatureException;

import java.util.Date;
import java.util.Map;


public class JwtTokenProvider {
    // 密钥（实际项目中需放在配置中心，网关和微服务共享）
//    @Value("${jwt.secret}")
    private static String secretKey="1222sjshjkjdskjdksdjksjfkdjkfjdjdkjfeiuruwuywuruew77syyysuuuwueyuwyeqeq9eiwodoiopposeowirdhshdwjejexxxdcsdsddwdwewewewesddfdjfkfkkfkdkfekejwe2323232";
//    private static String secretKey="2323";

    // 令牌过期时间（如2小时）
//    @Value("${jwt.expiration}")
    private static long expiration=3600000;

    public static void main(String[] args) {
        String aaa = generateToken("aaa","1","1");
        System.out.println(aaa);
    }
    // 生成令牌
    public static String generateToken(String username, String userId,String password) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + expiration);

        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(now)
                .setId(userId)
                .setClaims(Map.of("role","测试角色","userId",userId,"userName",username,"password",password))
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();
    }

    // 验证令牌并获取用户名
    public static String getUsernameFromToken(String token) {
        Claims claims = parseToken(token);
        return claims != null ? claims.get("userName", String.class) : null;
    }

    public static String getUserIdFromToken(String token) {
        Claims claims = parseToken(token);
        return claims != null ? claims.get("userId", String.class) : null;
    }

    // 验证令牌有效性
    public static boolean validateToken(String token,String username) {
        try {
            String tokenUsername = getUsernameFromToken(token);
            return username.equals(tokenUsername) && !isTokenExpired(token);
        } catch (Exception e) {
            // 令牌无效（过期、签名错误等）
            return false;
        }
    }

    // 检查令牌是否过期
    private static boolean isTokenExpired(String token) {
        Date expiration = Jwts.parserBuilder()
                .setSigningKey(secretKey)
                .build()
                .parseClaimsJws(token)
                .getBody()
                .getExpiration();
        return expiration.before(new Date());
    }

    /**
     * 从token中获取角色
     */
    public static String getRoleFromToken(String token) {
        Claims claims = parseToken(token);
        return claims != null ? claims.get("role", String.class) : null;
    }

    /**
     * 解析JWT token
     */
    public static Claims parseToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (SignatureException e) {
            // token无效
            return null;
        } catch (Exception e) {
            // 其他异常
            return null;
        }
    }
}
